//
//  LanguagesTableViewDataSource.m
//  LanguagesTeach
//
//  Created by Niel Santos on 12/16/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "LanguagesTableViewDataSource.h"
#import "RowTableCell.h"


@implementation LanguagesTableViewDataSource

- (id)init {
	
    if (self = [super init])
    {
		NSString *filePath = [[NSBundle mainBundle] pathForResource:@"languages_screen" ofType:@"xml" inDirectory: @"data"];
		NSURL *url = [NSURL fileURLWithPath:filePath];
		NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
		xmlLanguagesParser = [[XMLLanguagesParser alloc] init];
		xmlParser.delegate = xmlLanguagesParser;
		
		BOOL success = [xmlParser parse];
		[xmlParser release];
		
		if(success){
			NSLog(@"No errors found");
		}else{
			NSLog(@"Warning a error was found");
		}
    }
    return self;		
}


#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


// Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [xmlLanguagesParser.languages count];
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Language *language;
	NSString *imageDirectory;
	NSString *imagePath;
	
    static NSString *CellIdentifier = @"Cell";
    
    RowTableCell *cell = (RowTableCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[RowTableCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
		//accessory type
		cell.accessoryType= UITableViewCellAccessoryDetailDisclosureButton;			
    }
    
	// Configure the cell.
	language = [xmlLanguagesParser.languages objectAtIndex:indexPath.row];
	
	imageDirectory = [[NSString alloc] initWithFormat: @"data/%@",[language prefix]];
	imagePath = [[NSBundle mainBundle]
				 pathForResource:@"flag" 
				 ofType:@"png"
				 inDirectory: imageDirectory];
	[imageDirectory release];
	UIImage *ui = [[UIImage alloc] initWithContentsOfFile:imagePath];
	
	[cell.textLabel setText: [language title]];
	
	
	//set the image of the table cell
	cell.imageView.image = ui;
	[ui release];
	
	cell.prefix = language.prefix;
	
	
	
    return cell;
}


- (void)dealloc {
	[xmlLanguagesParser release];
    [super dealloc];
}

@end
